package com.cykj.order.service.impl;

import com.cykj.order.domain.BsOrders;
import com.cykj.order.domain.BsRegion;
import com.cykj.order.domain.dto.OrderProductDetailDto;
import com.cykj.order.domain.vo.BsOrdersVo;
import com.cykj.order.mapper.OrderMapper;
import com.cykj.order.service.IOrderService;
import com.cykj.order.service.OrderCacheService;
import com.cykj.order.service.OrderMessageService;
import com.cykj.order.util.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;

/**
 * 订单Service业务层处理
 * 
 * @author cykj
 * @date 2025-08-18
 */
@Service
public class OrderServiceImpl implements IOrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderCacheService orderCacheService;
    
    @Autowired
    private OrderMessageService orderMessageService;
    
    /**
     * 查询订单列表
     * @param bsOrders 订单查询条件
     * @return 订单集合
     */
    @Override
    public List<BsOrdersVo> selectOrderList(BsOrders bsOrders) {
        System.err.println(bsOrders);
        
        // 如果包含搜索条件，先清理缓存避免缓存命中错误
        if (hasSearchConditions(bsOrders)) {
            orderCacheService.clearOrderListCache();
        }
        
        // 先尝试从缓存获取订单列表
        List<BsOrdersVo> list = orderCacheService.getCachedOrderList(bsOrders);
        if (list != null) {
            System.err.println("从缓存获取订单列表，size=" + list.size());
            return list;
        }
        
        // 缓存不存在，查询数据库
        list = orderMapper.selectOrderList(bsOrders);
        System.err.println(list);
        
        if (list != null && !list.isEmpty()) {
            // 优化：先尝试从缓存获取地区数据
            List<BsRegion> tree = orderCacheService.getCachedRegionTree();
            if (tree == null) {
                // 缓存不存在，查询数据库并缓存
                List<BsRegion> bsRegions = orderMapper.selectRegion();
                tree = TreeUtil.buildTree(bsRegions);
                orderCacheService.cacheRegionTree(tree);
            }
            
            for (BsOrdersVo vo : list) {
                // 处理配送地址地区信息拼接
                Integer deliveryRegionId = vo.getDeliveryRegionId();
                if (deliveryRegionId != null) {
                    String fullDeliveryRegionName = TreeUtil.getFullRegionName(deliveryRegionId, tree);
                    String deliveryAddress = vo.getDeliveryAddress();
                    if (fullDeliveryRegionName != null && deliveryAddress != null) {
                        String completeDeliveryAddress = fullDeliveryRegionName + " " + deliveryAddress;
                        vo.setDeliveryAddress(completeDeliveryAddress);
                    } else if (fullDeliveryRegionName != null) {
                        vo.setDeliveryAddress(fullDeliveryRegionName);
                    }
                }
                
                // 处理商店地址地区信息拼接
                Integer shopRegionId = vo.getShopRegionId();
                if (shopRegionId != null) {
                    String fullShopRegionName = TreeUtil.getFullRegionName(shopRegionId, tree);
                    String shopAddressDetail = vo.getShopAddressDetail();
                    if (fullShopRegionName != null && shopAddressDetail != null) {
                        String completeShopAddress = fullShopRegionName + " " + shopAddressDetail;
                        vo.setShopAddressDetail(completeShopAddress);
                    } else if (fullShopRegionName != null) {
                        vo.setShopAddressDetail(fullShopRegionName);
                    }
                }
            }
            
            // 将处理后的结果缓存起来
            orderCacheService.cacheOrderList(bsOrders, list);
        }
        
        return list;
    }
    
    /**
     * 判断是否包含搜索条件
     * 
     * @param bsOrders 订单查询条件
     * @return 是否包含搜索条件
     */
    private boolean hasSearchConditions(BsOrders bsOrders) {
        return (bsOrders.getUserPhone() != null && !bsOrders.getUserPhone().isEmpty()) ||
               (bsOrders.getUserName() != null && !bsOrders.getUserName().isEmpty()) ||
               (bsOrders.getShopName() != null && !bsOrders.getShopName().isEmpty()) ||
               (bsOrders.getOrderNumber() != null && !bsOrders.getOrderNumber().isEmpty());
    }
    
    /**
     * 根据订单ID查询订单详情
     * 
     * @param id 订单ID
     * @return 订单扩展信息
     */
    @Override
    public BsOrdersVo selectOrderById(Long id) {
        // 先尝试从缓存获取
        BsOrdersVo vo = orderCacheService.getCachedOrderInfo(id);
        if (vo == null) {
            // 缓存不存在，查询数据库
            vo = orderMapper.selectOrderVoById(id);
            if (vo != null) {
                // 缓存订单信息
                orderCacheService.cacheOrderInfo(vo);
            }
        }
        if (vo != null) {
            // 处理手机号脱敏
            if (vo.getUserPhone() != null && vo.getUserPhone().length() == 11) {
                vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            
            // 处理地区信息拼接 - 使用缓存
            List<BsRegion> tree = orderCacheService.getCachedRegionTree();
            if (tree == null) {
                List<BsRegion> bsRegions = orderMapper.selectRegion();
                tree = TreeUtil.buildTree(bsRegions);
                orderCacheService.cacheRegionTree(tree);
            }
            
            // 处理配送地址地区信息拼接
            Integer deliveryRegionId = vo.getDeliveryRegionId();
            if (deliveryRegionId != null) {
                String fullDeliveryRegionName = TreeUtil.getFullRegionName(deliveryRegionId, tree);
                
                String deliveryAddress = vo.getDeliveryAddress();
                if (fullDeliveryRegionName != null && deliveryAddress != null) {
                    String completeDeliveryAddress = fullDeliveryRegionName + " " + deliveryAddress;
                    vo.setDeliveryAddress(completeDeliveryAddress);
                } else if (fullDeliveryRegionName != null) {
                    vo.setDeliveryAddress(fullDeliveryRegionName);
                }
            }
            
            // 处理商店地址地区信息拼接
            Integer shopRegionId = vo.getShopRegionId();
            if (shopRegionId != null) {
                String fullShopRegionName = TreeUtil.getFullRegionName(shopRegionId, tree);
                
                String shopAddressDetail = vo.getShopAddressDetail();
                if (fullShopRegionName != null && shopAddressDetail != null) {
                    String completeShopAddress = fullShopRegionName + " " + shopAddressDetail;
                    vo.setShopAddressDetail(completeShopAddress);
                } else if (fullShopRegionName != null) {
                    vo.setShopAddressDetail(fullShopRegionName);
                }
            }
        }
        return vo;
    }
    
    /**
     * 根据订单号查询订单详情
     * 
     * @param orderNumber 订单号
     * @return 订单扩展信息
     */
    @Override
    public BsOrdersVo selectOrderByOrderNumber(String orderNumber) {
        BsOrdersVo vo = orderMapper.selectOrderByOrderNumber(orderNumber);
        if (vo != null) {
            // 处理地区信息拼接 - 使用缓存
            List<BsRegion> tree = orderCacheService.getCachedRegionTree();
            if (tree == null) {
                List<BsRegion> bsRegions = orderMapper.selectRegion();
                tree = TreeUtil.buildTree(bsRegions);
                orderCacheService.cacheRegionTree(tree);
            }
            
            // 处理配送地址地区信息拼接
            Integer deliveryRegionId = vo.getDeliveryRegionId();
            if (deliveryRegionId != null) {
                String fullDeliveryRegionName = TreeUtil.getFullRegionName(deliveryRegionId, tree);
                String deliveryAddress = vo.getDeliveryAddress();
                if (fullDeliveryRegionName != null && deliveryAddress != null) {
                    String completeDeliveryAddress = fullDeliveryRegionName + " " + deliveryAddress;
                    vo.setDeliveryAddress(completeDeliveryAddress);
                } else if (fullDeliveryRegionName != null) {
                    vo.setDeliveryAddress(fullDeliveryRegionName);
                }
            }
            
            // 处理商店地址地区信息拼接
            Integer shopRegionId = vo.getShopRegionId();
            if (shopRegionId != null) {
                String fullShopRegionName = TreeUtil.getFullRegionName(shopRegionId, tree);
                String shopAddressDetail = vo.getShopAddressDetail();
                if (fullShopRegionName != null && shopAddressDetail != null) {
                    String completeShopAddress = fullShopRegionName + " " + shopAddressDetail;
                    vo.setShopAddressDetail(completeShopAddress);
                } else if (fullShopRegionName != null) {
                    vo.setShopAddressDetail(fullShopRegionName);
                }
            }
        }
        return vo;
    }
    
    /**
     * 根据订单ID查询订单商品详情（包含商品信息和订单明细）
     * 
     * @param orderId 订单ID
     * @return 订单商品详情集合
     */
    @Override
    public List<OrderProductDetailDto> selectOrderProductDetailsByOrderId(Long orderId) {
        List<OrderProductDetailDto> list = orderMapper.selectOrderProductDetailsByOrderId(orderId);

        if (list != null) {
            for (OrderProductDetailDto dto : list) {
                if (dto.getProductImage() == null || dto.getProductImage().trim().isEmpty()) {
                    dto.setProductImage("123.jpg");  //这里设置为你想要的默认图片
                }
            }
        }

        return list;
    }
    
    /**
     * 修改订单信息
     * 
     * @param bsOrders 订单信息
     * @return 结果
     */
    @Override
    public int updateOrder(BsOrders bsOrders) {
        // 获取原订单状态用于状态变更通知
        Integer oldStatus = null;
        if (bsOrders.getId() != null) {
            // 先尝试从缓存获取原状态
            oldStatus = orderCacheService.getCachedOrderStatus(bsOrders.getId());
            if (oldStatus == null) {
                // 缓存不存在，从数据库查询
                BsOrdersVo originalOrder = orderMapper.selectOrderVoById(bsOrders.getId());
                if (originalOrder != null) {
                    oldStatus = originalOrder.getStatus();
                }
            }
        }
        
        Integer newStatus = bsOrders.getStatus();
        if (newStatus != null) {
            if (newStatus == 1) {
                bsOrders.setPayTime(new Date());
            }
            if (newStatus == 2) {
                System.out.println("生成小票");
            }
            if (newStatus == 4) {
                bsOrders.setCompleteTime(new Date());
            }
        }
        
        int result = orderMapper.updateOrder(bsOrders);
        
        if (result > 0 && bsOrders.getId() != null) {
            // 更新成功后的后续处理
            if (newStatus != null) {
                // 更新缓存中的订单状态
                orderCacheService.cacheOrderStatus(bsOrders.getId(), newStatus);
                
                // 清除订单详情缓存，下次查询时重新加载
                orderCacheService.removeOrderInfoCache(bsOrders.getId());
                
                // 清除订单列表缓存，确保列表数据的一致性
                orderCacheService.clearOrderListCache();
                
                // 发送状态变更事件（如果状态确实发生了变化）
                if (oldStatus != null && !oldStatus.equals(newStatus)) {
                    orderMessageService.sendOrderStatusChangeEvent(
                        bsOrders.getId(), oldStatus, newStatus, "system"
                    );
                }
            }
        }
        
        return result;
    }
}
